import { useEffect, useState } from 'react'
import { getProductClassAll } from '@/api/goods'
export interface IOptionClass {
  classConfigId: string
  className: string
  childrenList?: IOptionClass[]
  classType: number
}
const useGetClassNames = () => {
  const [classIdOptions, setclassIdOptions] = useState<IOptionClass[]>([])
  const [tinyClassNames, settinyClassNames] = useState<string[]>([])
  useEffect(() => {
    getProductClassConfig()
  }, [])
  const getProductClassConfig = async () => {
    const res = await getProductClassAll<IOptionClass>()
    if (res.code === 200) {
      setclassIdOptions(res.data)
    }
  }
  const handleClassNameChange = (_: React.Key[], data: IOptionClass[]) => {
    if (data && data.length) {
      const node = data[data.length - 1]
      if (node.classType === 1) {
        const realNode = classIdOptions.find((item) => item.className === node.className)
        if (realNode) {
          const values = getClassIdsValues(realNode)
          return values
        } else {
          return []
        }
      } else {
        const values = getClassIdsValues(node)
        return values
      }
    } else {
      return []
    }
  }
  const getClassIdsValues = (node: IOptionClass) => {
    let values: string[] = []
    if (node.classType === 4) {
      values.push(node.className)
    }
    if (node.childrenList && node.childrenList.length > 0) {
      node.childrenList.forEach((child) => {
        values = values.concat(getClassIdsValues(child))
      })
    }
    settinyClassNames(values)
    return values
  }
  return { classIdOptions, settinyClassNames, tinyClassNames, handleClassNameChange }
}

export default useGetClassNames
